#!usr/bin/perl -w

use strict;
use Statistics::Descriptive;
use Statistics::Distributions;
die "usage:perl $0 <kaks.list> \n" unless @ARGV == 1;

open A,$ARGV[0];
print "ID\tSam:dN:dS\t...\tpop:dN/dS\tpvalue\n";
while(<A>){
	chomp;	my @a=split;	open IN,$a[1];
	#print "$a[-2]";
	$/="Model ";<IN>;	my $ln1=0;  my $ln2=0;	my %map;	my %tar;	my $dnds=0;
	while(my $inf=<IN>){
		chomp $inf;	my @b=split /\n+/,$inf;my @c=split /\s+/,$b[0];	
		if($c[0] eq "7:"){
			foreach my $k(0..$#b){
				if($b[$k]=~/lnL\(ntime:/){
					my @d=split /\s+/,$b[$k];
					$ln1=$d[-2];
				}
				if($b[$k]=~/tree length =/){
					my $v1=$b[$k+1];	my $v2=$b[$k+2];
					$v1=~s/://g;				$v2=~s/://g;	$v1=~s/\(//g;	$v2=~s/\(//g;					
					my @e1=split /\s+/,$v1;		my @e2=split /\s+/,$v2;
					foreach my $kk(0..$#e1){
						$map{$e1[$kk]}=$e2[$kk];
					}
				}
			}
		}
		if($c[0] eq "8:"){
			foreach my $k(@b){
				my @d=split /\s+/,$k;
				if($k=~/lnL\(ntime:/){
					$ln2=$d[-2];
				}
				if($k=~/(\d)\.\.(\d)/){
					my $num=@d;
					if($num == 10){
						if(exists $map{$2}){
							$tar{$map{$2}}=$d[-4].":".$d[-3];	
							$dnds=$d[-5];
						}
					}
				}
			}
		}
	}
	$/="\n";
	my $ml=2*abs($ln1-$ln2);
	my $chispro=Statistics::Distributions::chisqrprob (1,$ml);
	print "$a[0]";
	foreach my $k(sort keys %tar){
		print "\t$k:$tar{$k}";
	}
	print "\t$dnds\t$chispro\n";
	close IN;
}
close A;

